package com.jfinal.core;

import javax.servlet.FilterConfig;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.jfinal.util.SpringUtils;

/**
 * spring 必要的 filter
 * @ClassName: AbstractSpringFilter 
 * @author huangx
 * @date 2015年2月4日 下午12:04:41
 */
public abstract class AbstractSpring {
	private ApplicationContext context;

	/**
	 * @Title: 初始化 spring 上下文
	 * @param filterConfig
	 */
	public void initApplicationContext(FilterConfig filterConfig) {
		// 优先 加载 ContextLoaderListener
		this.context = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
		// 断言初始化成功
		Assert.notNull(context);
	}

	/**
	 * @Title: register JFinal
	 * @param configClass
	 * @return
	 */
	public Object registerJFinalBean(String configClass) {
		if (!context.containsBean(configClass)) {
			// 如果 spring 容器已存在则不注册
			// configClass 本身是个 className
			BeanDefinitionBuilder builder = SpringUtils.genericBean(configClass);
			AbstractBeanDefinition beanDefinition = builder.getRawBeanDefinition();
			beanDefinition.setScope(SpringUtils.SCOPE_SINGLETON);
			SpringUtils.registerBean(context, configClass, beanDefinition);
		}
		return context.getBean(configClass);
	}

	/**
	 * @Title: 获得 ApplicationContext  
	 * @return ApplicationContext 
	 * @throws
	 */
	public ApplicationContext getApplicationContext() {
		return context;
	}
}
